﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using YetAnotherChat.ChatCore.Interfaces;
using YetAnotherChat.ChatCore.Models;
using YetAnotherChat.ChatUI.ServiceImp;
using YetAnotherChat.EntityFrameworkDataAccess.RepositoryImp;
using YetAnotherChat.MemoryStorage.Imp;

namespace YetAnotherChat.ChatUI.Controllers
{
    public class MessageWebApiController : ApiController
    {
        private IChatMessageService _messageService;

        public MessageWebApiController()
        {
            _messageService = ChatMessageService.Instance;
           
        }

        /// <summary>
        /// Messages from ajax browsers
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage Chat(ChatMessage id)
        {
            id.ChatTopicGuidId = Guid.NewGuid();
            id.GuidId = Guid.NewGuid();
            _messageService.SaveMessages(new ChatMessage[] { id }, false);
            var response = Request.CreateResponse(HttpStatusCode.Created);
            return response;
        }

        /// <summary>
        /// Get messages 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
         [HttpGet]
        public HttpResponseMessage GetMessage(Guid userId, Guid topicId, DateTime fromTime)
        {
            fromTime = fromTime.ToUniversalTime();
            var messages = _messageService.GetMessages(userId, topicId, fromTime);
            var response = Request.CreateResponse<ChatMessage[]>(HttpStatusCode.OK, messages, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
            return response;
        }

        /// <summary>
        /// Message from tcp browsers
        /// </summary>
        /// <param name="messages"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage PostMessage(ChatMessage[] messages)
        {
            if(messages ==null)
                return Request.CreateResponse(HttpStatusCode.NoContent);
            _messageService.SaveMessages(messages, true);
            var response = Request.CreateResponse(HttpStatusCode.Created);
            return response;
        }
    }
}
